package conf

import (
	"context"
	"dbagent/internal/service"
	"flag"
	"os"
	"testing"
	"time"

	//"time"

	"github.com/BurntSushi/toml"
	"github.com/go-kratos/kratos/pkg/cache/redis"
	"github.com/go-kratos/kratos/pkg/conf/paladin"
	"github.com/go-kratos/kratos/pkg/log"
	bm "github.com/go-kratos/kratos/pkg/net/http/blademaster"

	//"github.com/go-kratos/kratos/pkg/net/rpc/warden"
	//xtime "github.com/go-kratos/kratos/pkg/time"
	// TODO "go.etcd.io/etcd/clientv3"
	//"google.golang.org/grpc"

	"github.com/go-kratos/kratos/pkg/database/sql"
	//"dbagent/pkg/yach"
	"dbagent/version"

	_ "github.com/go-sql-driver/mysql"
)

// Conf is global config
var Conf = &Config{}
var GetV bool
var Db *sql.DB
var BackupDb *sql.DB
var StartupTime time.Time

// 解决1.13版本testingn附加flag bug
var _ = func() bool {
	testing.Init()
	return true
}()

func init() {
	flag.BoolVar(&GetV, "v", false, "")
	flag.Parse()
	if GetV {
		version.Version()
		os.Exit(0)
	}
	if err := paladin.Init(); err != nil {
		panic(err)
	}

	if err := paladin.Watch("config.toml", Conf); err != nil {
		panic(err)
	}
	StartupTime = time.Now()
	log.Init(Conf.Log)

	dbagent := service.Dbagent{}
	go dbagent.RunV2(Conf.App.ReportUrl, Conf.BM.Addr, StartupTime, Conf.App.Interval)
	//go dbagent.GetDB(Conf.Mysql.Dsn)

	if Conf.BackupMySQL.DSN != "" {
		BackupDb = sql.NewMySQL(Conf.BackupMySQL)
	}

	/*Db = sql.NewMySQL(Conf.MySQL)
	err2 := Db.Ping(context.TODO())
	if err2 != nil {
		log.Error(err2.Error())
		dbagent := service.Dbagent{}
		dbagent.RunV2(Conf.App.ReportUrl, Conf.BM.Addr, StartupTime, Conf.App.Interval)
	} else {
		dbagent := service.Dbagent{}
		go dbagent.Run(Db, Conf.BM.Addr, StartupTime)
	}*/
	//dbagent.Create(Db, Conf.BM.Addr)
	//Conf.Etcd.DialTimeout = 10 * time.Second
	//Conf.Etcd.DialOptions = []grpc.DialOption{grpc.WithBlock()}
}

// Config .
type Config struct {
	App App
	//Etcd        *clientv3.Config
	Log         *log.Config
	BM          *bm.ServerConfig
	Redis       Redis
	Mysql       Mysql
	RateLimiter RateLimiter
	BackupMySQL *sql.Config `toml:"backup_mysql"`
}

// App config
type App struct {
	ScriptPath string   `toml:"script_path"`
	Username   string   `toml:"username"`
	Password   string   `toml:"password"`
	DeployEnv  string   `toml:"deploy_env"`
	AllowedIp  []string `toml:"allowed_ip"`
	ReportUrl  string   `toml:"report_url"`
	Interval   int      `toml:"interval"`
}

type Redis struct {
	redis.Config
	DB int `toml:"db"`
}

type Mysql struct {
	Addr string `toml:"addr"`
	Dsn  string `toml:"dsn"`
}

// RateLimiter 请求频率限制配置参数
type RateLimiter struct {
	Enable  bool  `toml:"enable"`
	Count   int64 `toml:"count"`
	RedisDB int   `toml:"redis_db"`
}

// Set .
func (c *Config) Set(text string) error {
	log.Infow(context.Background(), "log", "reload config")
	if _, err := toml.Decode(text, c); err != nil {
		panic(err)
	}
	return nil
}

func (c *Config) Close() {
	//dbagent := service.Dbagent{}
	//dbagent.Delete(Db, Conf.BM.Addr)
	Db.Close()
}
